//
//  SWChildProfileSettingViewController.swift
//  ChildStory
//
//  Created by linhan on 16/9/1.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWUserProfileSettingViewController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate,ImagePickerHelperDelegate
{
    private enum SettingAction:Int
    {
        case ChangeAvatar
        case ChangeScreenName
        case ChangeGender
        case ChangeBirthday
        case ChangeDesc
    }
    
    private class SettingItem
    {
        var title:String
        var sub:Bool
        var action:SettingAction
        var detail:Any?
        var icon:UIImage?
        
        init(title:String, sub:Bool, action:SettingAction)
        {
            self.title = title
            self.sub = sub
            self.action = action
        }
    }
    
    private let AvatarCellHeight:CGFloat = 132
    private let AvatarSize = CGSizeMake(200, 200)
    
    private var _account:SWMainAccount
    
    private var _settings:[SettingItem] = []
    
    private var _imagePicker:ImagePickerHelper?
    private var _pickerCell:FormPickerCell?
    private var _pickerIndexPath:IndexPath?
    
    lazy private var _toolBar:UIToolbar = UIToolbar()
    lazy private var _datePicker:UIDatePicker = UIDatePicker()
    
    lazy private var _tableView:UITableView = UITableView()
    
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        setup()
    }
    
    init(account:SWMainAccount)
    {
        _account = account
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK ============================================================================================
    //==============================            Public Method           ===============================
    //=================================================================================================
    
    deinit
    {
        trace("DEINIT ProfileSettingViewController")
    }
    
    private func setup()
    {
        title = "修改资料"
        
        //头像
        let avatarItem = SettingItem(title: "", sub: false, action:.ChangeAvatar)
        
        //昵称
        let screenNameItem = SettingItem(title: "昵称", sub: false, action:.ChangeScreenName)
        
        //性别
        let genderItem = SettingItem(title: "性别", sub: false, action:.ChangeGender)
        
        //生日
        let birthdayItem = SettingItem(title: "生日", sub: false, action:.ChangeBirthday)
        
        //生日
        let descItem = SettingItem(title: "个性签名", sub: false, action:.ChangeDesc)
        
        avatarItem.detail = _account.avatarURL ?? ""
        screenNameItem.detail = _account.screenName ?? ""
        genderItem.detail = _account.gender.rawValue
        birthdayItem.detail = _account.birthday
        descItem.detail = _account.desc
        
        
        _settings.append(avatarItem)
        _settings.append(screenNameItem)
        //_settings.append(genderItem)
        _settings.append(birthdayItem)
        _settings.append(descItem)
        
        view.backgroundColor = UIColor.white
        
        
        _tableView.frame = view.bounds
        _tableView.tableFooterView = UIView()
        _tableView.dataSource = self
        _tableView.delegate = self
        _tableView.backgroundColor = UIColor.white
        _tableView.separatorColor = UIColor(hex: 0xe2e2e2)
        self.view.addSubview(_tableView)
        
        _datePicker.frame = CGRectMake(0, 0, view.width, 150)
        _datePicker.datePickerMode = .date
        
        //工具栏
        let completeBtn = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(completeBtnTapped))
        let cancelBtn = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancelBtnTapped))
        let spaceBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
        
        _toolBar.sizeToFit()
        _toolBar.tintColor = UIColor.darkGray
        _toolBar.barTintColor = UIColor.white
        _toolBar.items = [cancelBtn, spaceBtn, completeBtn]
    }
    
    
    //MARK ============================================================================================
    //==============================            Delegate           ===============================
    //=================================================================================================
    
    //MARK ================================= UITableViewDelegate =========================
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _settings.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        return indexPath.row == 0 ? AvatarCellHeight : 55
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let index:Int = indexPath.row
        var cell:UITableViewCell?
        if let item = _settings.valueAt(index)
        {
            let action = item.action
            var identifier:String = "Cell"
            if action == .ChangeAvatar{
                identifier = "FormImageCell"
            }else if action == .ChangeBirthday{
                identifier = "FormPickerCell"
            }
            
            cell = tableView.dequeueReusableCell(withIdentifier: identifier)
            if cell == nil
            {
                if action == SettingAction.ChangeAvatar
                {
                    cell = FormImageCell(style: UITableViewCellStyle.default, reuseIdentifier: identifier, cellWidth: view.width, cellHeight: AvatarCellHeight)
                    cell?.selectionStyle = .none
                }
                else if action == SettingAction.ChangeBirthday
                {
                    _pickerCell = FormPickerCell(style: UITableViewCellStyle.value1, reuseIdentifier: identifier)
                    cell = _pickerCell
                }
                else
                {
                    cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: identifier)
                    cell?.backgroundColor = SWAppearanceManager.themeStyle.settingCellBackgroundColor
                }
                cell?.tintColor = SWAppearanceManager.themeStyle.cellDisclosureIndicatorColor
            }
            
            cell?.accessoryType = item.sub ? .disclosureIndicator : .none
            cell?.textLabel?.textColor = SWAppearanceManager.themeStyle.settingCellTextColor
            cell?.textLabel?.font = SWAppearanceManager.themeStyle.fontOfSize(15)
            cell?.detailTextLabel?.font = SWAppearanceManager.themeStyle.fontOfSize(15)
            if cell is FormImageCell
            {
                (cell as? FormImageCell)?.imageObject = item.detail
            }
            else
            {
                var detailString:String?
                if item.action == .ChangeGender
                {
                    let genderValue:Int = item.detail as? Int ?? SWGender.Unknow.rawValue
                    let gender = SWGender(rawValue: genderValue) ?? SWGender.Unknow
                    detailString = gender.descriptionString
                }
                else
                {
                    if let date = item.detail as? NSDate
                    {
                        detailString = dateToString(date)
                    }
                    else
                    {
                        detailString = item.detail as? String
                    }
                }
                cell?.detailTextLabel?.text = detailString
            }
            cell?.textLabel?.text = item.title
        }
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: true)
        let index:Int = indexPath.row
        if let item = _settings.valueAt(index)
        {
            if item.action == .ChangeAvatar
            {
                changeAvatar(index)
            }
            else if item.action == .ChangeScreenName
            {
                showTextInputViewController(index, title:item.title, text:item.detail as? String ?? "")
            }
            else if item.action == .ChangeDesc
            {
                showTextInputViewController(index, title:item.title, text:item.detail as? String ?? "", numberOfLines: 5)
            }
            else if item.action == .ChangeGender
            {
                changeGender(index)
            }
            
            if let cell = tableView.cellForRow(at:indexPath) as? FormPickerCell
            {
                if let date = _settings.valueAt(indexPath.row)?.detail as? Date
                {
                    _datePicker.date = date
                }
                
                cell.picker = _datePicker
                cell.toolBar = _toolBar
                cell.focus()
                _pickerCell = cell
                _pickerIndexPath = indexPath
            }
            else
            {
                _pickerCell?.resign()
                _pickerCell?.picker = nil
                _pickerCell?.toolBar = nil
                _pickerCell = nil
                _pickerIndexPath = nil
            }
        }
    }
    
    private func updateInfo(_ action:SettingAction, data:Any)
    {
        if action == .ChangeGender
        {
            //_child.gender = SWGender.getGender(responseValue:data as? Int ?? 0)
        }
        else if action == .ChangeScreenName
        {
            SWAccountManager.sharedManager().modifyAccountInfo(key: .screenName, value: data as? String ?? "")
        }
        else if action == .ChangeDesc
        {
            SWAccountManager.sharedManager().modifyAccountInfo(key: .desc, value: data as? String ?? "")
        }
    }
    
    private func changeAvatar(_ index:Int)
    {
        ActionSheet.show("设置头像", buttons: ["相册","摄像头","取消"], closeHandler: {index in
            
            if index == 0 || index == 1
            {
                self._imagePicker = ImagePickerHelper()
                self._imagePicker?.delegate = self
                self._imagePicker?.containerViewController = self
            }
            
            if index == 0
            {
                self._imagePicker?.presentPhotoLibraryPickerController()
            }
            else if index == 1
            {
                self._imagePicker?.presentCameraPickerController()
            }
            
            }, destructiveButtonIndex: -1, cancelButtonIndex: 2)
    }
    
    private func changeGender(_ index:Int)
    {
        ActionSheet.show("选择性别", buttons: ["男性","女性","取消"], closeHandler: {buttonIndex in
            
            if buttonIndex == 0
            {
                self._settings[index].detail = SWGender.Male.rawValue
                
                self._tableView.reloadRows(at:[IndexPath(row: index, section: 0)], with: UITableViewRowAnimation.none)
                self.updateInfo(.ChangeGender, data:SWGender.Male.rawValue)
            }
            else if buttonIndex == 1
            {
                self._settings[index].detail = UInt(SWGender.Female.rawValue)
                self._tableView.reloadRows(at:[IndexPath(row: index, section: 0)], with: UITableViewRowAnimation.none)
                self.updateInfo(.ChangeGender, data:SWGender.Female.rawValue)
            }
            }, destructiveButtonIndex: -1, cancelButtonIndex: 2)
    }
    
    private func showTextInputViewController(_ index:Int, title:String, text:String, numberOfLines:Int = 1)
    {
        let textInputViewController:SWTextInputViewController = SWTextInputViewController()
        textInputViewController.title = title
        textInputViewController.index = index
        textInputViewController.defaultText = text
        textInputViewController.numberOfLines = numberOfLines
        textInputViewController.completionCallback = {[weak self] text, index in
            if let strongSelf = self
            {
                strongSelf.textInputViewControllerCompletionCallback(text, index: index)
            }
        }
        let navigationController:UINavigationController = UINavigationController(rootViewController: textInputViewController)
        present(navigationController, animated: true, completion: nil)
    }
    
    private func textInputViewControllerCompletionCallback(_ text:String, index:Int)
    {
        if index >= 0 && index < _settings.count
        {
            self._settings[index].detail = text
            self._tableView.reloadRows(at:[IndexPath(row: index, section: 0)], with: UITableViewRowAnimation.none)
            if _settings[index].action == .ChangeScreenName
            {
                updateInfo(.ChangeScreenName, data:text)
            }
            else if _settings[index].action == .ChangeDesc
            {
                updateInfo(.ChangeDesc, data:text)
            }
        }
    }
    
    //MARK ================================= ImagePickerHelperDelegate =========================
    func imagePickerDidFinishPickingImage(image:UIImage?)
    {
        guard let image = image else{
            return
        }
        let avatarImage = Toucan.Resize.resizeImage(image, size: AvatarSize, fitMode: .crop)
        
        _settings.valueAt(0)?.detail = avatarImage
        _tableView.reloadRows(at:[IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.none)
        
        uploadImage(avatarImage).then(updateAvatar).then(avatarUpdateSuccess).onError(avatarUpdateFail)
    }
    
    private let _uploader:SWImageUploader = SWImageUploader()
    private func uploadImage(_ image:UIImage) -> Promise<String>
    {
        SVProgressHUD.show(withStatus: "头像保存中...")
        return Promise { resolve, reject in
            
            self._uploader.upload(image: image, quality: 0.6, successCallback: { url in
                resolve(url)
                },failCallback:{
                    reject(SWError.DefaultNetworkError)
            })
        }
    }
    
    private func updateAvatar(_ avatarURL:String) -> EmptyPromise
    {
        return Promise { resolve, reject in
            SWAccountManager.sharedManager().modifyAccountInfo(key: .avatarURL, value: avatarURL, notify: true, successCallback: { resolve() }, failCallback: { error in reject(error) })
        }//END promise
    }
    
    private func avatarUpdateSuccess()
    {
        DispatchQueue.main.async(execute: {
            SVProgressHUD.showSuccess(withStatus: "头像已保存")
        })
    }
    
    private func avatarUpdateFail(error:Error)
    {
        DispatchQueue.main.async(execute: {
            SVProgressHUD.showError(withStatus: "头像保存失败")
        })
    }
    
    private func dateToString(_ date:NSDate) -> String
    {
        return "\(date.year())年\(date.month())月\(date.day())日"
    }
    
    //MARK ============================================================================================
    //==============================               Selector             ===============================
    //=================================================================================================
    
    @objc private func completeBtnTapped()
    {
        if let indexPath = _pickerIndexPath
        {
            _settings.valueAt(indexPath.row)?.detail = _datePicker.date
            _tableView.reloadRows(at:[indexPath], with: .none)
            SWAccountManager.sharedManager().modifyAccountInfo(key: .birthday, value: _datePicker.date as NSDate)
        }
        _pickerCell?.resign()
    }
    
    @objc private func cancelBtnTapped()
    {
        _pickerCell?.resign()
    }
    
    
}
